package com.cls.quartz;

import com.cls.common.utils.FastDFSUtil;
import com.cls.system.entity.SysFile;
import lombok.RequiredArgsConstructor;
import org.csource.common.MyException;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import com.cls.system.service.ISysFileService;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * @author 魏卯卯
 */
@Component
@Configuration      //1.主要用于标记配置类，兼备Component的效果。
@EnableScheduling   // 2.开启定时任务
@RequiredArgsConstructor
public class FastdfsTask {
    private final ISysFileService sysFileService;

    /**
     * 3.添加定时任务,每天凌晨2点
     */
    @Scheduled(cron = "0 0 2 * * ?")
//    @Scheduled(cron = "0/5 * * * * ?")
    @Transactional(rollbackFor = Exception.class)
    public void delteFile() {
        Date date = new Date();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.DAY_OF_MONTH, -2);
        //前天
        date = calendar.getTime();
        List<SysFile> noFinishFile = sysFileService.findNoFinishFile(date);
        noFinishFile.forEach(item -> {
            sysFileService.removeById(item.getFileId());
            try {
                FastDFSUtil.fileDelete(item.getUrl());
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
    }

}
